/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/*
 * ListVentesPan.java
 *
 * Created on 21 août 2011, 17:05:15
 */
package app.views;

import app.App;
import app.events.eventobjects.VenteAddedEvent;
import app.events.eventobjects.VenteUpdatedEvent;
import app.events.eventobjects.VenteDeletedEvent;
import app.events.VenteListener;
import app.models.Client;
import app.models.Vente;
import app.tools.table.Column;
import java.awt.Point;
import java.awt.event.*;
import java.text.SimpleDateFormat;
import java.util.*;
import javax.swing.JMenuItem;
import javax.swing.JOptionPane;
import javax.swing.JPopupMenu;

/**
 *
 * @author Ghost
 */
public class ListVentesPan extends javax.swing.JPanel implements VenteListener, 
        ActionListener, MouseListener {

    private Date upper = Calendar.getInstance().getTime();
    private Date lower = Calendar.getInstance().getTime();
    private SimpleDateFormat sdf = new SimpleDateFormat("dd-MMM-yy HH:mm:ss");
    private List<Vente> ventes = new ArrayList<Vente>();
    
    private JPopupMenu popMenu;
    private JMenuItem miEdit;
    private JMenuItem miDelete;
    private JMenuItem miSelect;

    /**
     * Creates new form ListVentesPan
     */
    public ListVentesPan() {
        initComponents();

        tableVentes.addColumn(new Column<Vente, Integer>() {

            @Override
            public Integer getValue(Vente element) {
                return element.getId();
            }

            @Override
            public String getName() {
                return "no";
            }
        });

        tableVentes.addColumn(new Column<Vente, String>() {

            @Override
            public String getValue(Vente element) {
                return sdf.format(element.getDateV());
            }

            @Override
            public String getName() {
                return "Date";
            }
        });

        tableVentes.addColumn(new Column<Vente, Float>() {

            @Override
            public Float getValue(Vente element) {
                return element.getTotal();
            }

            @Override
            public String getName() {
                return "Total";
            }
        });

        tableVentes.addColumn(new Column<Vente, String>() {

            @Override
            public String getValue(Vente element) {
                Client c = element.getClient();
                if (c != null) {
                    return c.getDisplayName();
                } else {
                    return "Non fidèle";
                }
            }

            @Override
            public String getName() {
                return "Client";
            }
        });
        
        //Popupmenu preparation
        popMenu = new JPopupMenu("Hello");
        miEdit = new JMenuItem("Editer", App.createIcon("resources/note_edit.png"));
        miEdit.addActionListener(this);
        popMenu.add(miEdit);
        miDelete = new JMenuItem("Annuler", App.createIcon("resources/note_delete.png"));
        miDelete.addActionListener(this);
        popMenu.add(miDelete);
        /*miSelect = new JMenuItem("Selectionner", App.createIcon("resources/note_go.png"));
        miSelect.addActionListener(this);
        popMenu.add(miSelect);*/
        
        tableVentes.addMouseListener(this);

    }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jLabel1 = new javax.swing.JLabel();
        btOk = new javax.swing.JButton();
        jLabel2 = new javax.swing.JLabel();
        txtDateDebut = new org.jdesktop.swingx.JXDatePicker();
        txtDateFin = new org.jdesktop.swingx.JXDatePicker();
        tableVentes = new app.tools.table.SimpleTable2<Vente>();

        jLabel1.setText("Début:");

        btOk.setText("ok");
        btOk.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btOkActionPerformed(evt);
            }
        });

        jLabel2.setHorizontalAlignment(javax.swing.SwingConstants.RIGHT);
        jLabel2.setText("Fin:");

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(this);
        this.setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(tableVentes, javax.swing.GroupLayout.PREFERRED_SIZE, 0, Short.MAX_VALUE)
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(jLabel1)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(txtDateDebut, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                        .addComponent(jLabel2)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(txtDateFin, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(btOk)))
                .addContainerGap())
        );

        layout.linkSize(javax.swing.SwingConstants.HORIZONTAL, new java.awt.Component[] {jLabel1, jLabel2});

        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                        .addComponent(jLabel2, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                        .addComponent(txtDateFin, javax.swing.GroupLayout.PREFERRED_SIZE, 23, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addComponent(btOk))
                    .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                        .addComponent(txtDateDebut, javax.swing.GroupLayout.PREFERRED_SIZE, 23, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addComponent(jLabel1, javax.swing.GroupLayout.PREFERRED_SIZE, 23, javax.swing.GroupLayout.PREFERRED_SIZE)))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(tableVentes, javax.swing.GroupLayout.DEFAULT_SIZE, 151, Short.MAX_VALUE)
                .addContainerGap())
        );
    }// </editor-fold>//GEN-END:initComponents

    private void btOkActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btOkActionPerformed
        doSort();
    }//GEN-LAST:event_btOkActionPerformed

    private void doSort() {
        lower = txtDateDebut.getDate();
        upper = txtDateFin.getDate();

        List<Vente> vs = new ArrayList<Vente>(); //COPY!

        for (Object o : ventes) {
            if (o instanceof Vente) {
                Vente v = (Vente) o;
                
                Long date = v.getDateV().getTime();
                Long dateUp = upper.getTime() + (24 * 60 * 60 * 1000);//1 day
                Long dateLo = lower.getTime();
                if(date >= dateLo && date <= dateUp) {
                    vs.add(v);
                }
            }
        }

        tableVentes.setElements(vs);
    }

    private void sync() {
        txtDateDebut.setDate(lower);
        txtDateFin.setDate(upper);
        tableVentes.render();
    }
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton btOk;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private app.tools.table.SimpleTable2 tableVentes;
    private org.jdesktop.swingx.JXDatePicker txtDateDebut;
    private org.jdesktop.swingx.JXDatePicker txtDateFin;
    // End of variables declaration//GEN-END:variables

    @Override
    public void onVenteAdded(VenteAddedEvent vae) {
        Date curDate = vae.getVente().getDateV();
        if (curDate.after(upper)) {
            upper = curDate;
        }
        if (curDate.before(lower)) {
            lower = curDate;
        }
        tableVentes.addElement(vae.getVente());
        ventes.add(vae.getVente());
        sync();
    }

    @Override
    public void onVenteChanged(VenteUpdatedEvent vce) {
        System.out.println("/=======================\\ "
                + "        T O D O       "
                + "\\======================//");
    }

    @Override
    public void onVenteDeleted(VenteDeletedEvent vce) {
        System.out.println("/=======================\\ "
                + "        T O D O       "
                + "\\======================//");
    }
    
    

    @Override
    public void actionPerformed(ActionEvent e) {
        if(miDelete.equals(e.getSource())){
            Vente v = (Vente)tableVentes.getSelectedElement();
            if(v == null){
                App.displayMessage("Veuillez selectionner une vente SVP!", 
                        App.MESSAGE_TYPE.ERROR);
            }
            int response = JOptionPane.showConfirmDialog(this, 
                    "Voulez vous supprimer la vente no " + v.getId(), 
                    "Supprimer une vente?", JOptionPane.YES_NO_OPTION);
            
            if(response == JOptionPane.YES_OPTION){
                App.getInstance().getCahier().cancelVente(v);
                App.displayMessage("La vente a été annulée", 
                        App.MESSAGE_TYPE.INFO);
            }
        } else {
            App.displayMessage("Ta mère la pute", App.MESSAGE_TYPE.ERROR);
        }
    }

    @Override
    public void mouseClicked(MouseEvent e) {
        if(e.getButton() == MouseEvent.BUTTON3) {
            
            popMenu.show(tableVentes, e.getX(), e.getY());
        }
        if(e.getClickCount() == 2){
            //rien
        }
    }

    @Override
    public void mousePressed(MouseEvent e) {}

    @Override
    public void mouseReleased(MouseEvent e) {}

    @Override
    public void mouseEntered(MouseEvent e) {}

    @Override
    public void mouseExited(MouseEvent e) {}
}
